import { AddProductDetailModalComponent } from './add-product-detail-modal/add-product-detail-modal.component';
import { ProductInfoDTO, ProductDetailInfoDTO } from './../../../shared/service-proxy/service-proxies';
import { DictionaryDTO, ContainerDTO, LogisticsDTO } from '@shared/service-proxy/service-proxies';
import { Component, OnInit, Injector, ViewChild } from '@angular/core';
import { finalize } from 'rxjs/operators';
import { Router } from '@angular/router';
import {
  FormBuilder,
  FormControl,
  FormGroup,
  Validators
} from '@angular/forms';
import { ServiceProxy, SiteDTO } from '@shared/service-proxy/service-proxies';
import { AppComponentBase } from '@shared/common/app-component-base';
import { NzTableHelper } from '@shared/helpers/NzTableHelper';
import { NzModalService } from 'ng-zorro-antd';
import * as moment from 'moment';
import { FileUploader } from 'ng2-file-upload';
import { AppConsts } from '@shared/AppConsts';

@Component({
  selector: 'app-container-management',
  templateUrl: './container-management.component.html',
  styleUrls: ['./container-management.component.less']
})
export class ContainerManagementComponent extends AppComponentBase implements OnInit {
  @ViewChild('addProductDetailModal') addProductDetailModal: AddProductDetailModalComponent;
  @ViewChild('fileSelect') uploadImg: any;
  uploader: FileUploader;
  tableHelper: NzTableHelper;
  isOkLoading = false;
  keyword: string;
  company: string;
  isVisible = false;
  title: string;

  companyList: DictionaryDTO[] = [];

  validateForm: FormGroup;

  model: ContainerDTO = new ContainerDTO();

  constructor(
    injector: Injector,
    private fb: FormBuilder,
    private modalService: NzModalService,
    private router: Router,
    private _service: ServiceProxy) {

    super(injector);
    this.tableHelper = new NzTableHelper();

  }

  ngOnInit() {
    this.validateForm = this.fb.group({
      containerNo: [null, [Validators.required,
      // Validators.maxLength(255),
      Validators.pattern('^[A-Z]{4}[0-9]{7}$')]],
      containerSpecifications: [null, [Validators.nullValidator, Validators.maxLength(255)]],
      containerColor: [null, [Validators.nullValidator, Validators.maxLength(255)]],
      containerCompanyId: [null, [Validators.nullValidator]]
    });

    this.validateFormLogistic = this.fb.group({
      customCode: [null, [Validators.nullValidator, Validators.maxLength(255)]],
      logisticsCode: [null, [Validators.nullValidator, Validators.maxLength(255)]],
      loadingport: [null, [Validators.nullValidator, Validators.maxLength(255)]],
      containerCode: [null, [Validators.required, Validators.maxLength(255)]],
      importer: [null, [Validators.nullValidator, Validators.maxLength(255)]],
      importTime: [null, [Validators.nullValidator, Validators.maxLength(255)]],
      pod: [null, [Validators.nullValidator, Validators.maxLength(255)]],
      transporttool: [null, [Validators.nullValidator, Validators.maxLength(255)]],
      domesticdestination: [null, [Validators.nullValidator, Validators.maxLength(255)]],
      transportcompany: [null, [Validators.nullValidator, Validators.maxLength(255)]],
    });

    this.validateFormProduct = this.fb.group({
      customCode: [null, [Validators.required, Validators.maxLength(255)]],
      ctn: [null, [Validators.required]],
      pesobruto: [null, [Validators.required]],
      containerCode: [null, [Validators.required, Validators.maxLength(255)]],
      packagekind: [null, [Validators.required, , Validators.maxLength(255)]],
      pesoquido: [null, [Validators.required]],
      despachante: [null, [Validators.required, Validators.maxLength(255)]],
      du: [null, [Validators.required, Validators.maxLength(255)]],
      rdia: [null, [Validators.required, Validators.maxLength(255)]],
    })
    this.company = "";

    this.getCompanyList();
    this.load();
    this.initUploaders();
  }

  load(pageIndex?: number) {
    if (typeof pageIndex !== 'undefined') {
      this.tableHelper.pageIndex = pageIndex || 1;
    }
    this.getList();
  }

  sort(sort: { key: string, value: string }): void {
    this.tableHelper.setSorting = sort;
    this.load();
  }

  getList() {
    this._service.getPageContainersUsingGET(this.tableHelper.pageIndex, this.tableHelper.pageSize, this.keyword, this.company
    ).pipe(finalize(() => {
      this.tableHelper.loading = false;
    }))
      .subscribe((result) => {
        this.tableHelper.items = result.result.fieldList;
        this.tableHelper.totalCount = result.result.totalRow;
      });
  }


  getCompanyList() {
    this._service.getAllBySiteIdWarehouseDTOsUsingGET().subscribe(result => {
      this.companyList = result.result.fieldList;
    });
  }

  reset() {
    this.keyword = undefined;
    this.company = "";
    this.load();
  }

  showModal(id?: string): void {
    this.model = new ContainerDTO();
    this.isVisible = true;
    if (id) {

      this._service.getContainerUsingGET(id).subscribe(result => {
        this.model = result.result;
        if (!this.model.containerCompanyId) {
          this.model.containerCompanyId = "";
        }
      });
      this.title = this.l("edit");
    } else {
      this.validateForm.reset();
      this.model.containerCompanyId = "";
      this.title = this.l("create");
    }
  }


  handleOk(): void {
    this.isOkLoading = true;
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (this.validateForm.valid) { // 验证通过
      if (this.model.id) {
        this._service.updateContainerUsingPUT(this.model, this.model.id).subscribe(result => {
          this.isOkLoading = false;
          if (result.success) {
            this.message.success(this.l("save_success"));
            this.load();
            this.isVisible = false;
          }
          else {
            this.message.info(this.l(result.error.message));
          }
        }, error => {
          this.isOkLoading = false;
          this.message.error(this.l(error.message));
        });
      } else {

        this._service.createContainerUsingPOST(this.model).subscribe(result => {
          this.isOkLoading = false;
          if (result.success) {
            this.message.success(this.l("save_success"));
            this.load();
            this.isVisible = false;
          }
          else {
            this.message.info(this.l(result.error.message));
          }
        }, error => {
          this.isOkLoading = false;
          this.message.error(this.l(error.message));
        });
      }
    } else { // 验证未通过
      this.isOkLoading = false;
      this.message.error(this.l('verify_failed_please_check_the_form_item'));
    }
  }

  handleCancel(): void {
    this.isVisible = false;
  }


  //物流信息
  isVisibleLogistic: boolean = false;
  logistic: LogisticsDTO = new LogisticsDTO();
  validateFormLogistic: FormGroup;

  showLogisticModal(container: ContainerDTO): void {

    this._service.searchLogisticsUsingGET(container.id).subscribe(result => {
      this.logistic = result.result;
      if (!this.logistic) {
        this.logistic = new LogisticsDTO();
        this.logistic.containerCode = container.containerNo;
        this.logistic.containerId = container.id;
      }
    })

    this.isVisibleLogistic = true;
  }

  handleCancelLogistic(): void {
    this.isVisibleLogistic = false;
  }
  handleOKLogistic(): void {
    this.submitFormLogistic()
  }

  submitFormLogistic(): void {
    this.isOkLoading = true;
    for (const i in this.validateFormLogistic.controls) {
      this.validateFormLogistic.controls[i].markAsDirty();
      this.validateFormLogistic.controls[i].updateValueAndValidity();
    }

    if (this.validateFormLogistic.valid) {
      if (this.logistic.id) {
        this._service.updateLogisticsUsingPUT(this.logistic, this.logistic.id).subscribe(result => {
          this.isOkLoading = false;
          if (result.success) {
            this.message.success(this.l("save_success"));
            this.load();
            this.isVisibleLogistic = false;
          }
          else {
            this.message.info(this.l(result.error.message));
          }

        }, error => {
          this.isOkLoading = false;
          this.message.error(this.l(error.message));
        });
      } else {

        this._service.insertLogisticsUsingPOST(this.logistic).subscribe(result => {
          this.isOkLoading = false;
          if (result.success) {
            this.message.success(this.l("save_success"));
            this.load();
            this.isVisibleLogistic = false;
          }
          else {
            this.message.info(this.l(result.error.message));
          }
        }, error => {
          this.isOkLoading = false;
          this.message.error(this.l(error.message));
        });
      }
    }
    else {
      this.isOkLoading = false;
      this.message.create('error', this.l('verify_failed_please_check_the_form_item'));
    }
  }
  //货物信息
  validateFormProduct: FormGroup;
  isVisibleProduct: boolean = false;
  product: ProductInfoDTO = new ProductInfoDTO();

  showProductModal(container: ContainerDTO): void {
    this.isVisibleProduct = true;
    this._service.searchProductInfoByContainerIdUsingGET(container.id).subscribe(result => {
      this.product = result.result;

      if (!this.product) {
        this.product = new ProductInfoDTO();
        this.validateFormProduct.reset(); // 重置表单
        this.product.containerCode = container.containerNo;
        this.product.containerId = container.id;
        this.product.productDetailInfoDTOS = [];
      }
    })

  }

  handleOkProduct(): void {
    this.submitFormProduct()
  }

  handleCancelProduct(): void {
    // this.modalService.confirm({
    //   nzTitle: this.l('confirm'),
    //   nzContent: this.l('cancel_no_save'),
    //   nzOkText: 'OK',
    //   nzOnOk: () => {
    //     this.isVisibleProduct = false;
    //   },
    //   nzOnCancel: () => {

    //   },
    //   nzCancelText: this.l('cancel')

    // });
    this.isVisibleProduct = false;
  }

  submitFormProduct(): void {
    this.isOkLoading = true;
    for (const i in this.validateFormProduct.controls) {
      this.validateFormProduct.controls[i].markAsDirty();
      this.validateFormProduct.controls[i].updateValueAndValidity();
    }
    if (this.validateFormProduct.valid) {
      if (this.product.id) {
        this._service.updateProductInfoByIdUsingPUT(this.product, this.product.id).subscribe(result => {
          this.isOkLoading = false;
          if (result.success) {
            this.message.success(this.l('save_success'));
            this.load();
            this.isVisibleProduct = false;
          }
          else {
            this.message.info(this.l(result.error.message));
          }

        }, error => {
          this.isOkLoading = false;
          this.message.error(this.l(error.message));
        });
      } else {

        this._service.insertProductInfoUsingPOST(this.product).subscribe(result => {
          this.isOkLoading = false;
          if (result.success) {
            this.message.success(this.l('save_success'));
            this.load();
            this.isVisibleProduct = false;
          }
          else {
            this.message.info(this.l(result.error.message));
          }

        }, error => {
          this.isOkLoading = false;
          this.message.error(this.l(error.message));
        });
      }
    }
  }
  editProductDetail(p: ProductDetailInfoDTO) {
    this.index = this.product.productDetailInfoDTOS.findIndex(m => m == p);
    this.addProductDetailModal.show(this.product.id, p);
  }
  index: number = -1;
  addPdModal() {
    this.index = -1;
    this.addProductDetailModal.show(this.product.id, null, this.product.customCode);
  };

  addProductRow(p: ProductDetailInfoDTO) {
    debugger;
    if (this.index == -1) {
      var model = new ProductDetailInfoDTO();
      model.infoId = p.infoId;
      model.moeda = p.moeda;
      model.origin = p.origin;
      model.price = p.price;
      model.id = p.id;
      model.productName = p.productName;
      model.quantity = p.quantity;
      model.spc = p.spc;
      model.total = p.total;
      model.unidade = p.unidade;
      model.hsCode = p.hsCode;
      model.destination = p.hsCode;
      this.product.productDetailInfoDTOS = [...this.product.productDetailInfoDTOS, model];
    }

    else {
      this.product.productDetailInfoDTOS[this.index].infoId = p.infoId;
      this.product.productDetailInfoDTOS[this.index].moeda = p.moeda;
      this.product.productDetailInfoDTOS[this.index].origin = p.origin;
      this.product.productDetailInfoDTOS[this.index].price = p.price;
      this.product.productDetailInfoDTOS[this.index].id = p.id;
      this.product.productDetailInfoDTOS[this.index].productName = p.productName;
      this.product.productDetailInfoDTOS[this.index].quantity = p.quantity;
      this.product.productDetailInfoDTOS[this.index].spc = p.spc;
      this.product.productDetailInfoDTOS[this.index].total = p.total;
      this.product.productDetailInfoDTOS[this.index].unidade = p.unidade;
      this.product.productDetailInfoDTOS[this.index].hsCode = p.hsCode;
      this.product.productDetailInfoDTOS[this.index].destination = p.hsCode;
    }
  }
  createPath(item) {
    // Relative navigation back to the crises
    this.router.navigate(['/basic/containers/create', { id: item.id, containerNo: item.containerNo }]);
  }

  initUploaders(): void {
    this.uploader = new FileUploader({
      url: AppConsts.serverBaseUrl + '/api/siiat/v1/container/batchImport',
      method: 'POST',
      authToken: 'Bearer ' + abp.auth.getToken(),
      removeAfterUpload: true,
      autoUpload: true
    });
    this.uploader.onAfterAddingFile = (file) => {
      file.withCredentials = false;
    };

    this.uploader.onSuccessItem = (item, response, status) => {
      const ajaxResponse = JSON.parse(response);
      if (ajaxResponse.success) {
        this.message.success(this.l('upload_success'));
      } else {
        this.message.error(this.l(ajaxResponse.error.message));
      }

      this.uploader.destroy();
      this.initUploaders();
      this.imgCropper();
      this.load();
    };
    this.uploader.onErrorItem = (item, response, status) => {
      const ajaxResponse = JSON.parse(response);
      this.message.error(this.l(ajaxResponse.error.message))
      this.imgCropper();
    };

  }

  imgCropper() {
    // 一系列操作
    // 最后把input的value置空
    this.uploadImg.nativeElement.value = '';
  }
}
